package com.shwread.android.qysw.activity;

import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.team.TeamService;
import com.netease.nimlib.sdk.team.model.TeamMember;
import com.shwread.android.qysw10000243.R;
import com.shwread.android.ui.customview.WarnToast;
import com.shwread.android.ui.widget.TeamInfoGridView;

import java.util.List;

import logic.constants.Const;
import logic.util.ScreenUtil;
import logic.util.Util;


/**
 * @author xuzhijun
 * @date 2015年5月7日上午10:16:16
 */
public class NewInteractionCenterTeamInfoActivity
        extends
        BaseSimpleActivity
        implements
        OnClickListener
{
	private Context           mContext;
	//Title
	private TextView          tvTitle;
	private Button            btnBack;
	
	private RelativeLayout    expandLL;
	private RelativeLayout    dismissRay;
	private TeamInfoGridView  teamInfoGridView;
	private LinearLayout      teamNameLL, historyLL, clearLL;
	private TextView          teamNameTv;
	private Button            btnDismissTeam;
	private FrameLayout       gridFly;
	
	private boolean           isDraw         = false;
	private ImageView         expandImg;
	private int               gridInitHeight = 0;
	
	private List<TeamMember>  teamMembers;
	private TeamMemberAdapter adapter;
	private boolean           isManager      = true;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_interaction_center_team_info_activity);
		mContext = this;
		initView();
		initData();
		initListener();
	}
	
	private void initView() {
		//Title		
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		btnBack = (Button) findViewById(R.id.common_header_back);
		btnBack.setVisibility(View.VISIBLE);
		teamInfoGridView = (TeamInfoGridView) findViewById(R.id.new_interaction_center_team_info_members_grid_view);
		teamNameLL = (LinearLayout) findViewById(R.id.new_interaction_center_team_info_change_name_ll);
		teamNameTv = (TextView) findViewById(R.id.new_interaction_center_team_info_name_content_tv);
		historyLL = (LinearLayout) findViewById(R.id.new_interaction_center_team_info_history_ll);
		clearLL = (LinearLayout) findViewById(R.id.new_interaction_center_team_info_clear_ll);
		expandLL = (RelativeLayout) findViewById(R.id.new_interaction_center_team_info_expand_ll);
		gridFly = (FrameLayout) findViewById(R.id.new_interaction_center_team_info_members_grid_ll);
		expandImg = (ImageView) findViewById(R.id.new_interaction_center_team_info_expand_img);
		btnDismissTeam = (Button) findViewById(R.id.dismiss_team);
		dismissRay = (RelativeLayout) findViewById(R.id.dismiss_team_ray);
		gridFly.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener()
		{
			
			@Override
			public boolean onPreDraw() {
				if (!isDraw)
				{
					if (teamInfoGridView.getChildCount() > 4)
					{
						LayoutParams lp = gridFly.getLayoutParams();
						RelativeLayout view = (RelativeLayout) teamInfoGridView.getChildAt(0);
						gridInitHeight = view.getHeight() * 2 + gridFly.getPaddingBottom() + gridFly.getPaddingTop() + ScreenUtil.dip2px(getResources().getDimension(R.dimen.team_info_grid_verticalspacing));//TODO 
						lp.height = gridInitHeight;
						gridFly.setLayoutParams(lp);
					}
					isDraw = true;
				}
				return true;
			}
		});
		
	}
	
	private void initData() {
		isManager = Const.UserRole.equals("1") ? true : false;
		
		if (isManager)//客户经理专属
		{
			tvTitle.setText("聊天设置");
			gridFly.setVisibility(View.VISIBLE);
			expandLL.setVisibility(View.VISIBLE);
			teamNameLL.setVisibility(View.VISIBLE);
			dismissRay.setVisibility(View.VISIBLE);
			adapter = new TeamMemberAdapter();
//			initTeamMumber();
		}
		else
		{
			tvTitle.setText("聊天设置");
			gridFly.setVisibility(View.GONE);
			expandLL.setVisibility(View.GONE);
			teamNameLL.setVisibility(View.GONE);
			dismissRay.setVisibility(View.GONE);
		}
	}
	
	private void initTeamMumber() {
		NIMClient.getService(TeamService.class).queryMemberList("11184").setCallback(new RequestCallback<List<TeamMember>>()
		{
			@Override
			public void onSuccess(List<TeamMember> members) {
				teamMembers = members;
				adapter.setData(teamMembers);
				teamInfoGridView.setAdapter(adapter);
				Util.ToastShow(mContext, "成功");
			}
			
			@Override
			public void onException(Throwable arg0) {
				
			}
			
			@Override
			public void onFailed(int arg0) {
				Util.ToastShow(mContext, "失败");
			}
		});
		
	}
	
	private void initListener() {
		btnBack.setOnClickListener(this);
		expandLL.setOnClickListener(this);
		clearLL.setOnClickListener(this);
		historyLL.setOnClickListener(this);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_back:
				finish();
				break;
			case R.id.new_interaction_center_team_info_expand_ll:
				if (teamInfoGridView.getChildCount() > 4)
				{
					if (gridFly.getHeight() <= gridInitHeight)
					{
						startAnimation(gridFly, teamInfoGridView.getHeight() + gridFly.getPaddingBottom() + gridFly.getPaddingTop());
						startImageOpneRotateAnim();
						
					}
					else
					{
						startAnimation(gridFly, gridInitHeight);
						startImageCloseRotateAnim();
						
					}
				}
				break;
			case R.id.new_interaction_center_team_info_history_ll:
				Intent intent = new Intent();
				intent.setClass(mContext, NewInteractionCenterQueryChatActivity.class);
				mContext.startActivity(intent);
				break;
			case R.id.new_interaction_center_team_info_clear_ll:
				//			new WarnToast(mContext, "清空聊天记录失败,请稍后再试", R.drawable.new_i_clear_fail).show();
				new WarnToast(mContext, "已清空聊天记录", R.drawable.new_i_clear_suc).show();
				break;
			case R.id.dismiss_team://解散群组
				
				break;
		}
	}
	
	private class TeamMemberAdapter
	        extends
	        BaseAdapter
	{
		List<TeamMember>  tMembers;
		
		public void setData(List<TeamMember>  teamMembers)
		{
			this.tMembers = teamMembers;
		}
		
		@Override
		public int getCount() {
			return tMembers.size();
		}
		
		@Override
		public Object getItem(int position) {
			return tMembers.get(position);
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TeamMemberHolder holder;
			if (convertView == null)
			{
				convertView = LayoutInflater.from(mContext).inflate(R.layout.new_interaction_center_team_info_item, teamInfoGridView, false);
				holder = new TeamMemberHolder();
				holder.headerImg = (ImageView) convertView.findViewById(R.id.new_interaction_center_team_info_item_header_img);
				holder.ownerImg = (ImageView) convertView.findViewById(R.id.new_interaction_center_team_info_item_owner_img);
				holder.adminImg = (ImageView) convertView.findViewById(R.id.new_interaction_center_team_info_item_admin_img);
				holder.deleteImg = (ImageView) convertView.findViewById(R.id.new_interaction_center_team_info_item_delete_img);
				holder.nameTv = (TextView) convertView.findViewById(R.id.new_interaction_center_team_info_item_name_tv);
				convertView.setTag(holder);
			}
			else
			{
				holder = (TeamMemberHolder) convertView.getTag();
			}
			holder.nameTv.setText(tMembers.get(position).getTeamNick());
			return convertView;
		}
		
	}
	
	private class TeamMemberHolder
	{
		public ImageView headerImg;
		public ImageView        ownerImg, adminImg, deleteImg;
		public TextView         nameTv;
	}
	
	@SuppressLint ("NewApi")
	private void startAnimation(final View v, int endHeight) {
		final LayoutParams params = (LayoutParams) v.getLayoutParams();
		if (android.os.Build.VERSION.SDK_INT > 10)
		{
			ValueAnimator animation = ValueAnimator.ofInt(v.getHeight(), endHeight);
			animation.setDuration(400);
			animation.addUpdateListener(new AnimatorUpdateListener()
			{
				@Override
				public void onAnimationUpdate(ValueAnimator animation) {
					int height = Integer.parseInt(animation.getAnimatedValue().toString());
					params.height = height;
					v.setLayoutParams(params);
				}
			});
			animation.setInterpolator(new DecelerateInterpolator(2.0f));
			animation.start();
		}
	}
	
	private void startImageCloseRotateAnim() {
		Animation rotate = AnimationUtils.loadAnimation(this, R.anim.team_expand_totate_close);
		rotate.setDuration(400);
		rotate.setInterpolator(new DecelerateInterpolator(2.0f));
		rotate.setRepeatCount(0);
		rotate.setFillAfter(true);
		expandImg.startAnimation(rotate);
	}
	
	private void startImageOpneRotateAnim() {
		Animation rotate = AnimationUtils.loadAnimation(this, R.anim.team_expand_totate_open);
		rotate.setDuration(400);
		rotate.setInterpolator(new DecelerateInterpolator(2.0f));
		rotate.setRepeatCount(0);
		rotate.setFillAfter(true);
		expandImg.startAnimation(rotate);
	}
	
}
